#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Web工具应用程序
提供基于Python 2.7的JSON格式化工具
"""

import sys
import os
import logging

# 配置日志，避免编码问题
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler()]
)

# 解决Windows系统上的编码问题
if sys.version_info[0] == 2:
    # 设置默认编码为utf-8
    reload(sys)
    sys.setdefaultencoding('utf-8')

# 在Python 2.7中禁用Flask的自动编码转换，避免潜在问题
import werkzeug
werkzeug.urls.url_encode = lambda x, charset=sys.getdefaultencoding(), **k: werkzeug.urls.url_encode(x, charset=charset, **k)

from flask import Flask, render_template

# 处理 PyInstaller 打包后的资源路径
if getattr(sys, 'frozen', False):
    BASE_PATH = getattr(sys, '_MEIPASS', os.path.abspath('.'))
else:
    BASE_PATH = os.path.dirname(os.path.abspath(__file__))

# 创建Flask应用实例，显式指定模板与静态目录
template_folder = os.path.join(BASE_PATH, 'templates')
static_folder = os.path.join(BASE_PATH, 'static')
app = Flask(__name__, template_folder=template_folder, static_folder=static_folder, static_url_path='/static')

# 运行时日志，帮助定位路径问题
logging.info('BASE_PATH: %s', BASE_PATH)
logging.info('template_folder: %s', template_folder)
logging.info('static_folder: %s', static_folder)

@app.route('/')
def index():
    """首页路由，显示工具主页"""
    return render_template('index.html')

if __name__ == '__main__':
    """应用入口，启动Web服务器"""
    # 打包后禁用调试与自动重载，避免额外导入导致的缺失模块错误
    is_frozen = getattr(sys, 'frozen', False)
    debug_mode = False if is_frozen else True
    app.run(host='127.0.0.1', port=5000, debug=debug_mode, use_reloader=False)